package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.template.LOrderbillTemplate;
import com.ruoyi.system.vo.LOrderReportVo;
import com.ruoyi.system.vo.LOrderReportlParam;
import com.ruoyi.system.vo.LOrderbillVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.LOrderbillMapper;

import javax.validation.Validator;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.system.utils.Code.getCode;
import static com.ruoyi.system.utils.Code.getNowDate;

/**
 * 订单Service业务层处理
 *
 * @author zyb
 * @date 2022-01-02
 */
@Service
public class LOrderbillServiceImpl extends ServiceImpl<LOrderbillMapper, LOrderbill> implements ILOrderbillService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private ILEmployeeService employeeService;
    @Autowired
    private ILGoodsService goodsService;
    @Autowired
    private ILGuestService guestService;
    @Autowired
    protected Validator validator;

    /**
     * 查询订单
     *
     * @param billid 订单主键
     * @return 订单
     */
    @Override
    public LOrderbill selectLOrderbillByBillid(Integer billid) {
        return baseMapper.selectLOrderbillByBillid(billid);
    }

    /**
     * 查询订单列表
     *
     * @param lOrderbill 订单
     * @return 订单
     */
    @Override
    public List<LOrderbill> selectLOrderbillList(LOrderbill lOrderbill) {
        return baseMapper.selectLOrderbillList(lOrderbill);
    }

    @Override
    public List<LOrderbillVo> selectLOrderbillVoList(LOrderbill lOrderbill) {
        return baseMapper.selectLOrderbillVoList(lOrderbill);
    }

    /**
     * 新增订单
     *
     * @param lOrderbill 订单
     * @return 结果
     */
    @Override
    public int insertLOrderbill(LOrderbill lOrderbill) {
        if (!StringUtils.isNotBlank(lOrderbill.getBillcode())) {
            lOrderbill.setBillcode(String.valueOf(getBillCode()));
        }
        checkBillCode(lOrderbill);
        String str = getNowDate();
        int orderbill = redisCache.getCacheObject("orderbill" + str) == null ? 0 : redisCache.getCacheObject("orderbill" + str);
        lOrderbill.setCreateBy(String.valueOf(getUserId()));
        lOrderbill.setCreateTime(DateUtils.getNowDate());
        int i = baseMapper.insertLOrderbill(lOrderbill);
        orderbill++;
        redisCache.setCacheObject("orderbill" + str, orderbill, 1, TimeUnit.DAYS);
        return i;
    }

    //验证订单编号是否重复
    public void checkBillCode(LOrderbill lOrderbill) {
        String Billcode = lOrderbill.getBillcode();
        LOrderbill param = new LOrderbill();
        param.setBillcode(Billcode);
        List<LOrderbill> orderbills = selectLOrderbillList(param);
        if (orderbills.size() > 0) {
            String str = getNowDate();
            String type = sysConfigService.selectConfigByKey("order.bill.code.type");
            String billCode = type + "-" + str + "%";
            int billCodeNum = baseMapper.selectCountByBillCode(billCode);
            redisCache.setCacheObject("orderbill" + str, billCodeNum, 1, TimeUnit.DAYS);
            lOrderbill.setBillcode(String.valueOf(getBillCode()));
            checkBillCode(lOrderbill, billCodeNum);
        }


    }

    public void checkBillCode(LOrderbill lOrderbill, int billCodeNum) {
        String Billcode = lOrderbill.getBillcode();
        LOrderbill param = new LOrderbill();
        param.setBillcode(Billcode);
        List<LOrderbill> orderbills = selectLOrderbillList(param);
        if (orderbills.size() > 0) {
            String str = getNowDate();
            billCodeNum++;
            redisCache.setCacheObject("orderbill" + str, billCodeNum, 1, TimeUnit.DAYS);
            lOrderbill.setBillcode(String.valueOf(getBillCode()));
            checkBillCode(lOrderbill, billCodeNum);
        }
    }

    /**
     * 修改订单
     *
     * @param lOrderbill 订单
     * @return 结果
     */
    @Override
    public int updateLOrderbill(LOrderbill lOrderbill) {
        lOrderbill.setUpdateBy(String.valueOf(getUserId()));
        lOrderbill.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateLOrderbill(lOrderbill);
    }

    /**
     * 批量删除订单
     *
     * @param billids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteLOrderbillByBillids(Integer[] billids) {
        return baseMapper.deleteLOrderbillByBillids(billids);
    }

    /**
     * 删除订单信息
     *
     * @param billid 订单主键
     * @return 结果
     */
    @Override
    public int deleteLOrderbillByBillid(Integer billid) {
        return baseMapper.deleteLOrderbillByBillid(billid);
    }

    @Override
    public Object getBillCode() {
        String str = getNowDate();
        String type = sysConfigService.selectConfigByKey("order.bill.code.type");
        String billCode = type + "-" + str + "-";
        int orderbill = redisCache.getCacheObject("orderbill" + str) == null ? 0 : redisCache.getCacheObject("orderbill" + str);
        orderbill++;
        billCode = getCode(billCode, orderbill);
        return billCode;
    }

    @Override
    public List<LOrderbillVo> orderListNotExebilldetail(Long areaId,Long billid) {
        return baseMapper.orderListNotExebilldetail(areaId,billid);
    }
    @Override
    public String importOrder(List<LOrderbillTemplate> orderbillList, Boolean isUpdateSupport){
        if (StringUtils.isNull(orderbillList) || orderbillList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (LOrderbillTemplate template : orderbillList) {
            if(StringUtils.isNull(template.getBilldate())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、订单日期为空");
                continue;
            }
            if(StringUtils.isNull(template.getBookdate())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、预约时间为空");
                continue;
            }
            if(StringUtils.isNull(template.getTel())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、联系电话为空");
                continue;
            }
            if(StringUtils.isNull(template.getAddress())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、清运地址为空");
                continue;
            }
            LOrderbill orderbill = new LOrderbill();
            BeanUtils.copyProperties(template, orderbill);
            //货品
            LGoods goods = new LGoods();
            goods.setCode(template.getGoodsCode());
            Long goodsId = goodsService.getId(goods);
            if (goodsId > 0)orderbill.setGoodsid(goodsId);
            //客户
            LGuest guest = new LGuest();
            guest.setCode(template.getGuestCode());
            Long gid=guestService.getId(guest);
            if (gid > 0)orderbill.setGid(gid);
            //司机
            try {
                // 验证是否存在这个用户
                LOrderbill o = this.baseMapper.selectOne(new LambdaQueryWrapper<LOrderbill>().eq(LOrderbill::getBillcode, orderbill.getBillcode()));
                if (StringUtils.isNull(o)) {
                    BeanValidators.validateWithException(validator, orderbill);
                    this.insertLOrderbill(orderbill);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、订单 " + orderbill.getBillcode()+ " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, orderbill);
                    orderbill.setBillid(orderbill.getBillid());
                    this.updateLOrderbill(orderbill);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、订单 " + orderbill.getBillcode()+ " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、订单 " + orderbill.getBillcode()+" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单 " + orderbill.getBillcode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<LOrderReportVo> orderReport(LOrderReportlParam orderReportlParam) {
        return baseMapper.orderReport(orderReportlParam);
    }

    @Override
    public List<LOrderbillVo> orderNotWaybill(Long billid) {
        return baseMapper.orderNotWaybill(billid);
    }

}
